﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Heyo.Class.Helper.Network
{
    public class FileDownloaderWrap
    {

        public IEnumerable<FileDownloader> Downloads { get; }

        public int CompleteQuantity { get;private set; }
        public int SuccessQuantity { get;private set; }
        public int TotalQuantity { get; }
        public double Speed { get; private set; }
        public double Progress { get; private set; }

        public event Action<FileDownloaderWrap> OnCompleted;
        public event Action<FileDownloaderWrap> OnProgressChanged;

        public FileDownloaderWrap(params FileDownloader[] downloads)
        {

            Downloads = downloads;
            CompleteQuantity = 0;
            TotalQuantity = downloads.Length;
            foreach (FileDownloader info in downloads)
            {
               
                info.OnCompleted += d =>
                {
                    CompleteQuantity++;
                    if (d.Status == FileDownloader.DownloadStatus.Success)
                        SuccessQuantity++;

                    if (TotalQuantity == CompleteQuantity)
                        OnCompleted?.Invoke(this);
                };

                info.OnProgressChanged += d =>
                {
                    Progress = downloads.Average(t => t.Progress);
                    Speed = downloads.Sum(t => t.Speed);
                    OnProgressChanged?.Invoke(this);
                };
            }
        }

        public void BeginDownload(CancellationTokenSource tokenSource=null)
        {
            foreach (FileDownloader info in Downloads)
            {
                info.BeginDownload(tokenSource);
            }
        }
    }
}
